<template>
  <a-modal
    title="定时配置"
    :visible="visible"
    ok-text="确定"
    cancel-text="取消"
    width="800px"
    :mask-closable="false"
    centered
    @ok.stop="onOK"
    @cancel.stop="onCancel"
  >
    <div class="timing-content">
      <a-tabs
        v-if="selectedTables && selectedTables.length > 0"
        type="card"
        :model="currentTable"
      >
        <a-tab-pane v-for="tab in selectedTables" :key="tab" :tab="tab">
          <div class="content">
            <div
              v-if="
                tableColumMaps &&
                tableColumMaps[tab] &&
                tableColumMaps[tab].head.length === 0
              "
              class="not-support"
            >
              该数据表不支持定时设置
            </div>
            <a-form
              v-else
              :form="formMaps[tab]"
              :label-col="{ span: 8 }"
              :wrapper-col="{ span: 16 }"
            >
              <a-form-item label="是否开启定时同步">
                <a-switch
                  v-decorator="[
                    'needSchedule',
                    {
                      initialValue: false,
                    },
                  ]"
                  size="small"
                >
                </a-switch>
              </a-form-item>
              <a-form-item label="所依据的属性">
                <a-select
                  v-decorator="[
                    'incrementColumn',
                    {
                      rules: [{ required: true, message: '请选择' }],
                      initialValue: tableColumMaps[tab]
                        ? tableColumMaps[tab].head[0].name
                        : null,
                    },
                  ]"
                  class="tag-field"
                  size="small"
                  placeholder="请选择"
                  :disabled="notNeedSchedule(formMaps[tab])"
                >
                  <a-select-option
                    v-for="op in (tableColumMaps[tab]? tableColumMaps[tab].head : [])"
                    :key="op.name"
                    >{{ op.name }}
                  </a-select-option>
                </a-select>
              </a-form-item>
              <a-form-item label="更新频率">
                <div class="frequency">
                  <span class="label">每</span>
                  <a-select
                    v-decorator="[
                      'intervalOfHour',
                      {
                        rules: [{ required: true, message: '请选择频率' }],
                        initialValue: 1,
                      },
                    ]"
                    class="fre-number"
                    size="small"
                    placeholder="请选择"
                    :disabled="notNeedSchedule(formMaps[tab])"
                  >
                    <a-select-option v-for="i in 24" :key="i"
                      >{{ i }}
                    </a-select-option>
                  </a-select>
                  <a-select
                    v-decorator="[
                      'scheduleType',
                      {
                        rules: [{ required: true, message: '请选择频率' }],
                        initialValue: TimeUnit.day,
                      },
                    ]"
                    class="fre-unit"
                    :class="{
                      fix: scheduleType === TimeUnit.hour,
                    }"
                    size="small"
                    placeholder="请选择"
                    :disabled="notNeedSchedule(formMaps[tab])"
                    @change="timingTypeUnitChange"
                  >
                    <a-select-option :key="TimeUnit.hour">小时</a-select-option>
                    <a-select-option :key="TimeUnit.day">天</a-select-option>
                    <a-select-option :key="TimeUnit.week">周</a-select-option>
                  </a-select>
                </div>
              </a-form-item>
              <a-form-item label="开始日期">
                <a-date-picker
                  v-decorator="[
                    'beginDate',
                    {
                      rules: [{ required: true, message: '请选择' }],
                      initialValue: moment(new Date()),
                    },
                  ]"
                  placeholder="请选择"
                  format="YYYY-MM-DD"
                  size="small"
                  :disabled="notNeedSchedule(formMaps[tab])"
                >
                </a-date-picker>
              </a-form-item>
              <a-form-item
                v-show="scheduleType === TimeUnit.day"
                label="设置时间"
              >
                <a-select
                  v-decorator="[
                    'hourOfDay',
                    {
                      rules: [{ required: true, message: '请选择时间' }],
                      initialValue: 0,
                    },
                  ]"
                  size="small"
                  style="width: 100px;"
                  :disabled="notNeedSchedule(formMaps[tab])"
                >
                  <a-select-option v-for="i in 24" :key="i - 1"
                    >{{ i - 1 }}时
                  </a-select-option>
                </a-select>
                <a-select
                  v-decorator="[
                    'minuteOfHour',
                    {
                      rules: [{ required: true, message: '请选择时间' }],
                      initialValue: 0,
                    },
                  ]"
                  size="small"
                  style="width: 100px;"
                  :disabled="notNeedSchedule(formMaps[tab])"
                >
                  <a-select-option v-for="i in 60" :key="i - 1"
                    >{{ i - 1 }}分
                  </a-select-option>
                </a-select>
              </a-form-item>
              <a-form-item
                v-show="scheduleType === TimeUnit.hour"
                label="设置时间"
              >
                <a-select
                  v-decorator="[
                    'minuteOfHour',
                    {
                      rules: [{ required: true, message: '请选择时间' }],
                      initialValue: 0,
                    },
                  ]"
                  size="small"
                  style="width: 180px;"
                  :disabled="notNeedSchedule(formMaps[tab])"
                >
                  <a-select-option v-for="i in 60" :key="i - 1"
                    >{{ i - 1 }}分
                  </a-select-option>
                </a-select>
              </a-form-item>

              <a-form-item
                v-show="scheduleType === TimeUnit.week"
                label="设置时间"
              >
                <a-select
                  v-decorator="[
                    'daysOfWeek',
                    {
                      rules: [{ required: true, message: '请选择时间' }],
                      initialValue: 'SUN',
                    },
                  ]"
                  size="small"
                  style="width: 180px;"
                  :disabled="notNeedSchedule(formMaps[tab])"
                >
                  <a-select-option v-for="item in weekDays" :key="item.value"
                    >{{ item.label }}
                  </a-select-option>
                </a-select>
              </a-form-item>
            </a-form>
          </div>
        </a-tab-pane>
      </a-tabs>
      <div
        v-if="!(selectedTables && selectedTables.length > 0)"
        class="empty-info"
      >
        <img alt="" src="@/assets/view/dataview-empty.svg" />
        <p>
          暂未发现有效导入字段 (列) ! <br />
          请在 " <strong> 导入数据</strong> " 根据数据类型导入数据
        </p>
      </div>
    </div>
  </a-modal>
</template>
<script lang="ts">
/**
 * 数据库定时配置
 */
import { Vue, Component, Watch, Prop } from 'vue-property-decorator'
import DataUploadStore from '@/store/modules/data-upload'
import moment from 'moment'
import { isArray } from '@/util/data-view-table-helper'
import { cloneDeep } from 'lodash'
import { getTablesHead } from '@/api/data'

/** 关联自增字段可用类型 */
const associatedFieldTypes = new Set([
  'tinyint',
  'smallint',
  'mediumint',
  'int',
  'integer',
  'bigint',
  'float',
  'double',
  'decimal',
  'date',
  'time',
  'year',
  'datetime',
  'timestamp',
])

const defaultFormData: any = {
  beginDate: moment(new Date()),
  daysOfWeek: 'SUN',
  hourOfDay: 0,
  incrementColumn: '',
  minuteOfHour: 0,
  needSchedule: false,
  intervalOfHour: 1,
  scheduleType: 'day',
}

const TimeUnit = {
  hour: 'hour',
  day: 'day',
  week: 'week',
}

@Component({
  name: 'timing-setting-modal',
  components: {},
})
export default class TimingSettingModal extends Vue {
  @Prop({ type: Boolean, default: false }) visible!: boolean

  @Prop({
    type: Object,
    default() {
      return null
    },
  })
  selectedTableData!: object

  // 标题
  public title: string = '定时设置'
  public scheduleType: string = TimeUnit.day
  public TimeUnit: any = TimeUnit
  // 表单
  private formMaps: any = {}
  public tableColumMaps: any = {}
  // 当前表格
  public currentTable: string = ''
  // 星期
  public weekDays: Array<any> = [
    {
      label: '星期一',
      value: 'MON',
    },
    {
      label: '星期二',
      value: 'TUE',
    },
    {
      label: '星期三',
      value: 'WED',
    },
    {
      label: '星期四',
      value: 'THU',
    },
    {
      label: '星期五',
      value: 'FRI',
    },
    {
      label: '星期六',
      value: 'SAT',
    },
    {
      label: '星期日',
      value: 'SUN',
    },
  ]

  public get moment() {
    return moment
  }

  // 外部数据选中的表
  public get selectedTables() {
    return DataUploadStore.selectedTables
  }

  /**
   * 是否定时
   * @param form
   */
  public notNeedSchedule(form: any) {
    return !form.getFieldValue('needSchedule')
  }

  /**
   * 已经保存的定时配置
   */
  public get timingSettingMaps() {
    return DataUploadStore.timingSettingMaps
  }

  /**
   * 获取表格数据
   */
  public getTablesHeadData() {
    const passData = {
      ...DataUploadStore.databaseConfig,
      tableNames: this.selectedTables,
    }
    getTablesHead({ data: passData }).then((response: any) => {
      if (response.data.code === 100) {
        // 过滤可用类型
        response.data.result.forEach((tableHeadInfo: any) => {
          const headSet = tableHeadInfo as any
          headSet.head = (headSet.head as Array<any>).filter((item) => {
            return associatedFieldTypes.has(item.type as string)
          })
          this.tableColumMaps[tableHeadInfo.tableName] = headSet
        })
      }
    })
  }

  /**
   * 监听选中的表
   */
  @Watch('selectedTables', { immediate: true })
  getSelectedTables(newValue: any) {
    if (isArray(newValue) && newValue.length > 0) {
      this.currentTable = (newValue as Array<string>)[0] as string
      newValue.forEach((tableName: string) => {
        if (!this.formMaps[tableName]) {
          this.formMaps[tableName] = this.$form.createForm(this, {
            name: tableName,
          })
        }
      })
      this.getTablesHeadData()
    } else {
      this.currentTable = ''
    }
  }

  /**
   * 时间单位变更事件
   */
  public timingTypeUnitChange(value: string) {
    this.scheduleType = value
  }

  /**
   * 确认
   */
  public onOK() {
    const tableNames = Object.keys(this.formMaps)
    const formDataMaps = {} as any
    Object.values(this.formMaps).forEach((form: any, index: number) => {
      let formData = form.getForm().getFieldsValue()
      if (Object.keys(formData).length === 0) {
        formData = cloneDeep(defaultFormData)
      }
      formDataMaps[tableNames[index]] = formData
    })
    this.$emit('confirm', {
      timing: formDataMaps,
    })
  }

  public onCancel() {
    this.$emit('cancel')
  }
}
</script>
<style lang="less" scoped>
.timing-content {
  background-color: #fff;
  display: flex;
  flex-direction: column;
  font-size: 14px;
  height: 352px;
}

/deep/ .tag-field {
  width: 180px;
}

.frequency {
  /deep/ .ant-select {
    display: inline-block;
    width: 100px;

    // 时间频率数
    &.fre-number {
      margin: 0 10px;
      width: 60px;
    }

    // 时间单位
    &.fre-unit {
      width: 60px;

      &.fix {
        width: 64px;
      }

      .ant-select-selection {
        border-width: 0 !important;

        &:hover {
          border-width: 0 !important;
        }
      }

      .ant-select-selection__rendered {
        margin-right: 0;
      }

      .ant-select-arrow {
        right: 12px;

        .anticon {
          display: inline-block;

          &.anticon-down {
            border: 5px solid transparent;
            border-top-color: #888;
            height: 0;
            width: 0;
          }

          svg {
            display: none !important;
          }
        }
      }
    }
  }
}

/* 为空 */
.empty-info {
  align-items: center;
  display: flex;
  flex-direction: column;
  height: 100%;
  justify-content: center;
  text-align: center;
}

.content {
  height: auto;
  margin: 0 auto;
  width: 360px;
}

.not-support {
  height: 197px;
  line-height: 197px;
  margin: auto;
  text-align: center;
  width: 100%;
}
</style>
